<template>
  <div class="order-detail-page">
    <!-- 顶部导航 -->
    <van-nav-bar
      :title="`订单详情(${order?.orderNumber})`"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="$router.go(-1)"
    >
      <template #right>
        <van-icon name="more-o" size="18" />
      </template>
    </van-nav-bar>

    <!-- 订单状态卡片 -->
    <div class="status-card" v-if="order">
      <div class="status-header">
        <span class="status-label">订单状态</span>
        <van-tag :type="getStatusTagType(order.status)" size="medium">
          {{ getStatusText(order.status) }}
        </van-tag>
      </div>

      <div class="progress-bar">
        <van-steps :active="getActiveStep" active-color="#1989fa" direction="vertical">
          <van-step v-for="(step, index) in order.progressSteps" :key="index">
            <div class="step-content">
              <h3>{{ step.name }}</h3>
              <p>{{ step.description }}</p>
              <div v-if="step.timestamp" class="step-time">
                <van-icon name="clock-o" />
                <span>{{ formatDate(step.timestamp) }}</span>
              </div>
            </div>
          </van-step>
        </van-steps>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="info-card" v-if="order">
      <h3 class="card-title">订单信息</h3>

      <div class="info-grid">
        <div class="info-item">
          <label>下单时间</label>
          <span>{{ formatDateTime(order.createTime) }}</span>
        </div>
        <div class="info-item">
          <label>下单人</label>
          <span>{{ order.customerName }} ({{ order.customerId }})</span>
        </div>
        <div class="info-item">
          <label>操作员</label>
          <span>{{ order.operator || '系统自动' }}</span>
        </div>
        <div class="info-item">
          <label>冷库仓号</label>
          <span>{{ order.storageRoom }}</span>
        </div>
        <div class="info-item">
          <label>存储位置</label>
          <span>{{ order.storageLocation || 'C区-201号冷柜' }}</span>
        </div>
        <div class="info-item">
          <label>存储时长</label>
          <span>{{ order.storageDuration }}天</span>
        </div>
        <div class="info-item">
          <label>预计出库时间</label>
          <span>{{
            order.expectedReleaseDate ? formatDate(order.expectedReleaseDate) : '暂未确定'
          }}</span>
        </div>
        <div class="info-item">
          <label>订单金额</label>
          <span class="price">¥{{ order.totalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <!-- 样品列表 -->
    <div class="samples-card" v-if="order">
      <h3 class="card-title">样品信息</h3>

      <div class="sample-item" v-for="(sample, index) in order.samples" :key="sample.id">
        <div class="sample-header">
          <span class="index">#{{ index + 1 }}</span>
          <span class="name">{{ sample.name }}</span>
          <span class="type">{{ sample.type }}</span>
        </div>
        <div class="sample-info">
          <div class="quantity-box">
            <van-icon name="coupon-o" />
            <span>{{ sample.quantity }} {{ sample.unit }}</span>
          </div>
          <div class="storage-box">
            <van-icon name="gem-o" />
            <span>{{ order.storageRoom }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 检测报告 -->
    <div class="report-card" v-if="order && order.testReport">
      <h3 class="card-title">检测报告</h3>

      <div class="report-info">
        <div class="report-header">
          <div class="report-number">
            <span class="label">报告编号:</span>
            <span>{{ order.testReport.reportNumber }}</span>
          </div>
          <van-tag type="success" size="medium">已完成</van-tag>
        </div>

        <div class="report-details">
          <div class="report-item">
            <label>检测员</label>
            <span>{{ order.testReport.tester }}</span>
          </div>
          <div class="report-item">
            <label>生成时间</label>
            <span>{{ formatDateTime(order.testReport.generateTime) }}</span>
          </div>
          <div class="report-item">
            <label>检测结论</label>
            <span :class="getConclusionClass(order.testReport.conclusion)">
              {{ order.testReport.conclusion }}
            </span>
          </div>
        </div>

        <van-button block type="primary" icon="down" class="download-btn" @click="downloadReport">
          下载检测报告 (PDF)
        </van-button>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="fixed-footer" v-if="order">
      <van-button
        v-if="order.status === 'pending'"
        type="danger"
        class="action-btn"
        @click="cancelOrder"
      >
        取消订单
      </van-button>

      <van-button
        v-if="order.status === 'testing' && !order.testReport"
        type="primary"
        class="action-btn"
        @click="simulateGenerateReport"
      >
        生成检测报告
      </van-button>

      <van-button
        v-if="order.status === 'storing' || order.status === 'completed'"
        plain
        type="primary"
        class="action-btn"
        @click="goStorageLocation"
      >
        查看冷库位置
      </van-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { Toast, Dialog, ImagePreview } from 'vant'
import dayjs from 'dayjs'
import type { OrderDetail, OrderStatus } from '../types/orderList'

export default defineComponent({
  name: 'OrderDetail',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const order = ref<OrderDetail | null>(null)

    // 获取状态文本
    const getStatusText = (status: OrderStatus): string => {
      const statusMap: Record<OrderStatus, string> = {
        pending: '待处理',
        processing: '处理中',
        storing: '储存中',
        testing: '检测中',
        completed: '已完成',
        cancelled: '已取消',
      }
      return statusMap[status] || status
    }

    // 获取状态标签类型
    const getStatusTagType = (status: OrderStatus) => {
      const typeMap: Record<OrderStatus, string> = {
        pending: 'primary',
        processing: 'warning',
        storing: 'primary',
        testing: 'warning',
        completed: 'success',
        cancelled: 'danger',
      }
      return typeMap[status] || 'default'
    }

    // 获取当前进度
    const getActiveStep = computed(() => {
      if (!order.value) return -1
      const firstUncompleted = order.value.progressSteps.findIndex((step) => !step.completed)
      return firstUncompleted !== -1 ? firstUncompleted : order.value.progressSteps.length - 1
    })

    // 格式化日期时间
    const formatDateTime = (date: Date): string => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    // 格式化日期
    const formatDate = (date: Date): string => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    // 获取检测结论样式
    const getConclusionClass = (conclusion: string) => {
      return conclusion === '合格' ? 'conclusion-pass' : 'conclusion-fail'
    }

    // 下载报告
    const downloadReport = () => {
      Toast('正在下载检测报告...')
      // 实际项目中这里应该是下载文件的逻辑
      setTimeout(() => {
        Toast('检测报告下载完成')
      }, 1500)
    }

    // 取消订单
    const cancelOrder = () => {
      Dialog({
        title: '取消订单',
        message: '确定要取消这个订单吗？此操作不可撤销。',
      }).then(() => {
        if (order.value) {
          order.value.status = 'cancelled'
          Toast('订单已取消')
          // 更新进度状态
          order.value.progressSteps.forEach((step) => {
            if (!step.completed) {
              step.completed = true
              step.description = '订单已取消，未执行此步骤'
            }
          })
        }
      })
    }

    // 查看冷库位置
    const goStorageLocation = () => {
      ImagePreview([
        require('@/assets/mock-storage-map.png'), // 在实际项目中替换为真实路径
      ])
      Toast('冷库位置图已展示')
    }

    // 模拟生成检测报告
    const simulateGenerateReport = () => {
      if (!order.value) return

      // 模拟生成报告过程
      const loadingToast = Toast({
        type: 'loading',
        duration: 0,
        message: '正在生成检测报告...',
        forbidClick: true,
      })

      // 模拟API请求
      setTimeout(() => {
        const report: any = {
          id: 'REP' + Date.now().toString().slice(-8),
          reportNumber: 'REP2023' + Math.floor(Math.random() * 10000),
          generateTime: new Date(),
          conclusion: Math.random() > 0.2 ? '合格' : '不合格',
          tester: '张检测员',
          attachmentUrl: '/reports/sample.pdf',
        }

        // 更新订单状态
        order.value.testReport = report
        order.value.status = 'completed'

        // 更新进度
        order.value.progressSteps.forEach((step) => {
          if (!step.completed) {
            step.completed = true
            step.timestamp = new Date()
          }
        })

        Toast.clear()
        Toast('检测报告生成完成')
      }, 2000)
    }

    // 初始化模拟数据
    const initMockData = () => {
      const orderId = route.query.id as string
      console.log('45555', route)
      const mockOrders: OrderDetail[] = [
        {
          id: '6',
          orderNumber: 'ORD20230815001',
          createTime: new Date(2023, 7, 15, 10, 30),
          totalAmount: 12000.5,
          status: 'processing',
          customerName: '张先生',
          customerId: 'CUST00234',
          storageRoom: 'C-2-101',
          operator: '王操作员',
          storageLocation: 'C区-201号冷柜',
          storageDuration: 60,
          expectedReleaseDate: new Date(2023, 9, 15),
          samples: [
            { id: 's1', name: '抗生素注射剂', type: '药品', quantity: 100, unit: '盒' },
            { id: 's2', name: '疫苗样本', type: '生物样本', quantity: 50, unit: '管' },
            { id: 's3', name: '血样', type: '生物样本', quantity: 200, unit: '瓶' },
          ],
          progressSteps: [
            {
              name: '订单创建',
              description: '客户提交订单，等待审核',
              completed: true,
              timestamp: new Date(2023, 7, 15, 10, 30),
            },
            {
              name: '订单审核',
              description: '后台审核订单信息',
              completed: true,
              timestamp: new Date(2023, 7, 15, 11, 15),
            },
            {
              name: '样品接收',
              description: '等待客户寄送样品',
              completed: false,
            },
            {
              name: '样品存储',
              description: '样品进入冷库存储',
              completed: false,
            },
            {
              name: '样品检测',
              description: '实验室进行样品检测',
              completed: false,
            },
            {
              name: '报告生成',
              description: '生成检测报告',
              completed: false,
            },
            {
              name: '订单完成',
              description: '订单全部流程完成',
              completed: false,
            },
          ],
        },
        {
          id: '3',
          orderNumber: 'ORD20230817012',
          createTime: new Date(2023, 7, 17, 9, 15),
          totalAmount: 23000.75,
          status: 'testing',
          customerName: '王女士',
          customerId: 'CUST00567',
          storageRoom: 'B-3-312',
          operator: '李操作员',
          storageLocation: 'B区-312号冷冻柜',
          storageDuration: 90,
          expectedReleaseDate: new Date(2023, 10, 15),
          samples: [
            { id: 's1', name: '冷冻食品样本', type: '食品', quantity: 30, unit: '盒' },
            { id: 's2', name: '乳制品样本', type: '食品', quantity: 50, unit: '盒' },
          ],
          progressSteps: [
            {
              name: '订单创建',
              description: '客户提交订单，等待审核',
              completed: true,
              timestamp: new Date(2023, 7, 17, 9, 15),
            },
            {
              name: '订单审核',
              description: '后台审核订单信息',
              completed: true,
              timestamp: new Date(2023, 7, 17, 10, 30),
            },
            {
              name: '样品接收',
              description: '客户寄送样品已接收',
              completed: true,
              timestamp: new Date(2023, 7, 18, 14, 20),
            },
            {
              name: '样品存储',
              description: '样品进入冷库存储',
              completed: true,
              timestamp: new Date(2023, 7, 18, 15, 45),
            },
            {
              name: '样品检测',
              description: '实验室进行样品检测',
              completed: true,
              timestamp: new Date(2023, 7, 21, 9, 10),
            },
            {
              name: '报告生成',
              description: '生成检测报告',
              completed: false,
            },
            {
              name: '订单完成',
              description: '订单全部流程完成',
              completed: false,
            },
          ],
        },
        {
          id: '4',
          orderNumber: 'ORD20230818005',
          createTime: new Date(2023, 7, 18, 16, 45),
          totalAmount: 15600.0,
          status: 'completed',
          customerName: '李医生',
          customerId: 'CUST00321',
          storageRoom: 'D-4-104',
          operator: '张操作员',
          storageLocation: 'D区-104号冷柜',
          storageDuration: 30,
          expectedReleaseDate: new Date(2023, 8, 18),
          samples: [
            { id: 's1', name: '基因样本A型', type: '生物样本', quantity: 20, unit: '管' },
            { id: 's2', name: '细胞样本', type: '生物样本', quantity: 40, unit: '管' },
          ],
          testReport: {
            id: 'REP20230822001',
            reportNumber: 'REP20230822001',
            generateTime: new Date(2023, 7, 22, 14, 30),
            conclusion: '合格',
            tester: '王检测员',
            attachmentUrl: '/reports/REP20230822001.pdf',
          },
          progressSteps: [
            {
              name: '订单创建',
              description: '客户提交订单，等待审核',
              completed: true,
              timestamp: new Date(2023, 7, 18, 16, 45),
            },
            {
              name: '订单审核',
              description: '后台审核订单信息',
              completed: true,
              timestamp: new Date(2023, 7, 18, 17, 20),
            },
            {
              name: '样品接收',
              description: '客户寄送样品已接收',
              completed: true,
              timestamp: new Date(2023, 7, 19, 10, 15),
            },
            {
              name: '样品存储',
              description: '样品进入冷库存储',
              completed: true,
              timestamp: new Date(2023, 7, 19, 14, 30),
            },
            {
              name: '样品检测',
              description: '实验室进行样品检测',
              completed: true,
              timestamp: new Date(2023, 7, 21, 11, 20),
            },
            {
              name: '报告生成',
              description: '生成检测报告',
              completed: true,
              timestamp: new Date(2023, 7, 22, 14, 30),
            },
            {
              name: '订单完成',
              description: '订单全部流程完成',
              completed: true,
              timestamp: new Date(2023, 7, 22, 15, 10),
            },
          ],
        },
      ]

      const foundOrder = mockOrders.find((o) => o.id === orderId)
      if (foundOrder) {
        order.value = foundOrder
      }
    }

    // 生命周期钩子
    onMounted(() => {
      initMockData()
    })

    return {
      order,
      getStatusText,
      getStatusTagType,
      getActiveStep,
      formatDateTime,
      formatDate,
      getConclusionClass,
      downloadReport,
      cancelOrder,
      goStorageLocation,
      simulateGenerateReport,
    }
  },
})
</script>

<style lang="scss" scoped>
.order-detail-page {
  padding-bottom: 70px;
  background-color: #f7f9fb;
  min-height: 100vh;

  .status-card {
    background: white;
    border-radius: 10px;
    margin: 16px;
    padding: 16px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

    .status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .status-label {
        font-weight: bold;
        color: #333;
        font-size: 16px;
      }
    }

    .progress-bar {
      :deep(.van-step) {
        padding-left: 26px;
      }

      :deep(.van-step__circle) {
        top: 16px;
      }

      :deep(.van-step__line) {
        top: 30px;
        bottom: -10px;
      }

      .step-content {
        padding: 8px 0 16px;

        h3 {
          margin: 0 0 5px;
          font-size: 15px;
        }

        p {
          margin: 0 0 5px;
          color: #666;
          font-size: 13px;
        }

        .step-time {
          color: #969799;
          font-size: 12px;
          display: flex;
          align-items: center;

          .van-icon {
            margin-right: 4px;
          }
        }
      }
    }
  }

  .info-card,
  .samples-card,
  .report-card {
    background: white;
    border-radius: 10px;
    margin: 16px;
    padding: 16px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

    .card-title {
      margin-top: 0;
      margin-bottom: 16px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f7f8fa;
      font-size: 16px;
      color: #333;
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;

    .info-item {
      display: flex;
      flex-direction: column;

      label {
        color: #969799;
        font-size: 13px;
        margin-bottom: 4px;
      }

      span {
        font-size: 14px;
        word-break: break-all;

        &.price {
          color: #ee0a24;
          font-weight: bold;
        }
      }
    }
  }

  .samples-card {
    .sample-item {
      background: #f9fafb;
      border-radius: 8px;
      margin-bottom: 12px;
      padding: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .sample-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .index {
          background: #1989fa;
          color: white;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 13px;
          margin-right: 10px;
        }

        .name {
          font-weight: bold;
          font-size: 15px;
          margin-right: 8px;
        }

        .type {
          color: #1989fa;
          background: rgba(25, 137, 250, 0.1);
          padding: 3px 8px;
          border-radius: 10px;
          font-size: 12px;
        }
      }

      .sample-info {
        display: flex;

        .quantity-box,
        .storage-box {
          display: flex;
          align-items: center;
          background: white;
          padding: 5px 10px;
          border-radius: 15px;
          margin-right: 10px;
          font-size: 13px;

          .van-icon {
            margin-right: 5px;
            color: #969799;
          }
        }
      }
    }
  }

  .report-card {
    .report-info {
      .report-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f7f8fa;

        .report-number {
          .label {
            color: #969799;
            margin-right: 8px;
          }
        }
      }

      .report-details {
        margin-bottom: 20px;

        .report-item {
          display: flex;
          justify-content: space-between;
          padding: 8px 0;
          font-size: 14px;

          label {
            color: #969799;
          }

          .conclusion-pass {
            color: #07c160;
            font-weight: bold;
          }

          .conclusion-fail {
            color: #ee0a24;
            font-weight: bold;
          }
        }
      }

      .download-btn {
        border-radius: 20px;
      }
    }
  }

  .fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 16px;
    background: white;
    border-top: 1px solid #f7f8fa;
    display: flex;
    gap: 10px;

    .action-btn {
      flex: 1;
      border-radius: 20px;
    }
  }
}
</style>
